package com.caits.lbs.framework.services.mina;

import org.apache.log4j.Logger;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

/**
 * <p>
 * ClientIoHandler
 * </p>
 * <p>
 * 用途：客户端处理基础实现类
 * </p>
 * 
 * @author 周华彬(zhouhuabin@ctfo.com, zhou_hua_bin@163.com)
 * @version 0.0.1 2011-6-20
 *          <table style="border:1px solid gray;">
 *          <tr>
 *          <th width="100px">版本号</th>
 *          <th width="100px">动作</th>
 *          <th width="100px">修改人</th>
 *          <th width="100px">修改时间</th>
 *          </tr>
 *          <!-- 以 Table 方式书写修改历史 -->
 *          <tr>
 *          <td>0.0.0</td>
 *          <td>创建类</td>
 *          <td>zhb</td>
 *          <td>2011-6-20 下午03:25:18</td>
 *          </tr>
 *          <tr>
 *          <td>0.0.1</td>
 *          <td>创建类</td>
 *          <td>zhb</td>
 *          <td>2011-6-20 下午03:25:18</td>
 *          <td>0.0.2</td>
 *          <td>修改类</td>
 *          <td>xxx</td>
 *          <td>x年x月x日</td>
 *          </tr>
 *          </table>
 */
public class ClientIoHandler extends IoHandlerAdapter {

	/** TODO */
	private Logger log = Logger.getLogger(getClass());
	
	/** 客户端业务处理接口 */
	private IClientService client;

	/** 收到数据是否需要回应 */
	private boolean returnCmdConfirm = false;

	/**
	 * 构造器
	 */
	public ClientIoHandler() {
	}

	@Override
	public void sessionCreated(IoSession session) throws Exception {

	}

	@Override
	public void sessionOpened(IoSession session) throws Exception {
		session.write(client.login());
	}

	@Override
	public void messageReceived(IoSession session, Object message)
			throws Exception {
		log.debug("接收到信息为:" + message);
		Object ret = client.handleMessage(session, message);
		log.debug("处理后的信息为:" + ret);
		if (returnCmdConfirm)
			session.write(ret);
	}

	@Override
	public void sessionIdle(IoSession session, IdleStatus status)
			throws Exception {
		if (status.equals(IdleStatus.BOTH_IDLE)) {
			session.write("NOOP");
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.apache.mina.core.service.IoHandlerAdapter#sessionClosed(org.apache
	 * .mina.core.session.IoSession)
	 */
	@Override
	public void sessionClosed(IoSession session) throws Exception {
		// TODO Auto-generated method stub
		super.sessionClosed(session);
	}

	/**
	 * 设置属性 client 的值，IClientService类型
	 * 
	 * @param client
	 *            the client to set
	 */
	public void setClient(IClientService client) {
		this.client = client;
	}

	/**
	 * 获取属性client的值
	 * 
	 * @return the client : ClientService
	 */
	public IClientService getClient() {
		return client;
	}

	public boolean isReturnCmdConfirm() {
		return returnCmdConfirm;
	}

	public void setReturnCmdConfirm(boolean returnCmdConfirm) {
		this.returnCmdConfirm = returnCmdConfirm;
	}

}
